package com.wxtf.platform.main.contraceptives;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wxtf.platform.interfaces.CommonsCallProvider;
import com.wxtf.platform.plugins.user.UserBean;
import com.wxtf.platform.supers.LogicBase;
import com.wxtf.platform.tools.AccessDataBaseUtil;
import com.wxtf.platform.tools.ConstantInfoHelper;
import com.wxtf.platform.tools.FormatUtil;
/**
 * <li>Title: TmaIncomeAction.java</li>
 * <li>Project: baseplatform</li>
 * <li>Package: com.wxtf.platform.main.contraceptives</li>
 * <li>Description: 药具入库</li>
 * <li>Copyright: Copyright (c) 2012</li>
 * <li>Company: wxthtf Technologies </li>
 * <li>Created on Jul 5, 2012 10:08:48 AM</li>
 *
 * @author liu_zhaojun
 * @version 1.0.0.0
 *
 */
public class TmaIncomeAction extends LogicBase implements CommonsCallProvider {
	
	private static Log log = LogFactory.getLog(TmaIncomeAction.class);
	
	public TmaIncomeAction(String jsonArray) {

	}
	
	/** 
	 * 描述：delete 删除入库记录
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 10, 2012  5:12:42 PM
	 * @author liu_zhaojun
	 */
	@Override
	public Object delete(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String id = jsonObject.getString("ids");
		String[] ids = id.split(",");
		String sql = "delete from TMA_INCOME_MAIN where TMAIM_ID = ?";
		AccessDataBaseUtil.deleteByIds(sql, ids);
		return "\"删除成功\"";
	}

	/** 
	 * 描述：insert 增加入库记录
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 10, 2012  5:12:42 PM
	 * @author liu_zhaojun
	 */
	@Override
	public Object insert(Object jsonArray) throws Exception {		
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));		
		String tmaim_code = jsonObject.getString("tmaim_code");
		sql = "select count(*) from TMA_INCOME_MAIN where tmaim_code=?";
		int hasId = AccessDataBaseUtil.queryForInt(sql,new Object[]{tmaim_code});
		if(hasId>0){
			return "\"入库编号不能重复\"";
		}					
		String tmaim_id = AccessDataBaseUtil.getPKUUID();
		UserBean user = (UserBean)(this.getRequest()).getSession().getAttribute("userBean");
		String org_id = user.getCurOrgId();
		String create_by = user.getUserId();
		String create_time = FormatUtil.getCurentDateTime();
		List<String> list = new ArrayList<String>();
		StringBuffer buff = new StringBuffer("insert into TMA_INCOME_MAIN(tmaim_id,org_id,tmaim_type,tmaim_is_valid,tmaim_code,tmaim_time,create_by,create_time,last_modify_by,last_modify_time) values(");
		buff.append("'").append(tmaim_id).append("'")
		.append(",'").append(org_id).append("'")
		.append(",'").append(jsonObject.getString("tmaim_type")).append("'")
		.append(",'").append(jsonObject.getString("tmaim_is_valid")).append("'")
		.append(",'").append(tmaim_code).append("'")
		.append(",'").append(jsonObject.getString("tmaim_time")).append("'")
		.append(",'").append(create_by).append("'")
		.append(",'").append(create_time).append("'")
		.append(",'").append(create_by).append("'")
		.append(",'").append(create_time).append("')");
		list.add(buff.toString());
		buff.setLength(0);
		String ids = jsonObject.getString("ids");
		array = JSONArray.fromObject(ids);
		for(int i=0;i<array.size();i++){
			jsonObject = array.getJSONObject(i);
			buff.append("insert into TMA_INCOME_DETAIL(tmaid_id,tmaim_id,tmad_id,tmaid_num,create_by,create_time,last_modify_by,last_modify_time) values(")
			.append("'").append(AccessDataBaseUtil.getPKUUID()).append("'")
			.append(",'").append(tmaim_id).append("'")
			.append(",'").append(jsonObject.getString("tmad_id")).append("'")
			.append(",'").append(jsonObject.getString("tmaid_num")).append("'")
			.append(",'").append(create_by).append("'")
			.append(",'").append(create_time).append("'")
			.append(",'").append(create_by).append("'")
			.append(",'").append(create_time).append("')");
			list.add(buff.toString());
			buff.setLength(0);
		}
		AccessDataBaseUtil.executeSQLUpdate(list);
		return "\"新建成功\"";
	}

	@Override
	public Object update(Object jsonArray) throws Exception {
		return null;
	}
	
	/** 
	 * 描述：select 查询入库记录
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 10, 2012  5:12:42 PM
	 * @author liu_zhaojun
	 */
	@Override
	public Object select(Object jsonArray) throws Exception {
		UserBean user = (UserBean)(this.getRequest()).getSession().getAttribute("userBean");
		String org_id = user.getCurOrgId();
		sql = " from tma_income_main a,t_department b,t_user c where a.org_id=b.department_id and a.create_by=c.user_id and a.org_id=?";
		String countSql = "select count(*)" + sql;
		String querySql = "select a.tmaim_id,b.caption as org_id,a.tmaim_code,a.tmaim_time,a.tmaim_type,c.caption as create_by,a.tmaim_is_valid" + sql;
		String[] fields = {"tmaim_id","org_id","tmaim_code","tmaim_time","tmaim_type","create_by","tmaim_is_valid"};
		return AccessDataBaseUtil.query4SQLPagging(fields, countSql, querySql, this.getPage(), this.getPagesize(), new Object[]{org_id});
	}
	
	@Override
	public Object run() {
		Object msg = "";
		try {
			if ("queryPage".equals(this.getMethodName())) {// 列表
				msg = this.select(this.getLogicData());
			} else if ("save".equals(this.getMethodName())) {// 添加
				msg = this.insert(this.getLogicData());
			} else if ("delete".equals(this.getMethodName())) {// 删除
				msg = this.delete(this.getLogicData());
			} else if ("detail".equals(this.getMethodName())) {// 查询入库明细记录
				msg = this.detail(this.getLogicData());
			} else if ("selectTmGeneralDictionary".equals(this.getMethodName())) {// 查询药具类型
				msg = this.selectTmGeneralDictionary(this.getLogicData());
			} else if ("selectTmaDictionary".equals(this.getMethodName())) {// 根据药具种类查询药具名称
				msg = this.selectTmaDictionary(this.getLogicData());
			} else if ("selectTmaDictionaryById".equals(this.getMethodName())) {// 根据药具Id查询药具信息
				msg = this.selectTmaDictionaryById(this.getLogicData());
			} else {
				msg = "\"没有【" + this.getMethodName() + "】该方法\"";
			}
			if(msg == null || "[null]".equals(msg)){
				msg = "\"\"";
			}
			if(msg.toString().startsWith("{") || msg.toString().startsWith("[")){
				return msg;
			}
			msg = ConstantInfoHelper.generateJSONString(msg.toString());
		} catch (Exception e) {
			msg = "操作失败，请联系管理员";
			msg = ConstantInfoHelper.generateJSONString(ConstantInfoHelper.JSON_HEAD, ConstantInfoHelper.getFailResultDetail(msg.toString()), false);
			log.error(e, e);
		} finally {
			this.clear();
		}
		return msg.toString();
	}
	
	/** 
	 * 描述：detail 查询入库明细记录
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 10, 2012  5:12:42 PM
	 * @author liu_zhaojun
	 */
	public Object detail(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String tmaim_id = jsonObject.getString("tmaim_id");
		sql = " from TMA_DICTIONARY t inner join TMA_INCOME_DETAIL d on t.tmad_id=d.tmad_id and d.tmaim_id=? left join tm_general_dictionary g on t.tmad_kind=g.tmgd_id";
		String querySql = "select t.tmad_name,g.tmgd_name,t.tmad_company_name,t.tmad_price,d.tmaid_num" + sql;
		String[] fields = {"tmad_name","tmgd_name","tmad_company_name","tmad_price","tmaid_num"};
		array = JSONArray.fromObject(AccessDataBaseUtil.query(fields, querySql, new Object[]{tmaim_id}));
		return "{\"Rows\":" + array.toString() + "}";
	}
	
	/** 
	 * 描述：selectTmGeneralDictionary 查询药具类型
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 10, 2012  5:12:42 PM
	 * @author liu_zhaojun
	 */
	public Object selectTmGeneralDictionary(Object jsonArray) throws Exception {		
		sql = "select a.tmgd_id,a.tmgd_name from tm_general_dictionary a inner join tma_dictionary b on a.tmgd_id=b.tmad_kind and b.reserve1='1' and b.tmad_status='0' where a.tmgd_is_valid='1' and a.tmgd_type='105' group by a.tmgd_id order by a.tmgd_order_num";
		String[] fields = {"tmgd_id","tmgd_name"};
		JSONArray array = JSONArray.fromObject(AccessDataBaseUtil.query(fields, sql, null));
		return array;
	}
	
	/** 
	 * 描述：selectTmaDictionary 根据药具种类查询药具名称
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 10, 2012  5:12:42 PM
	 * @author liu_zhaojun
	 */
	public Object selectTmaDictionary(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String tmgd_id = jsonObject.getString("tmgd_id");
		sql = "select tmad_id,tmad_name from tma_dictionary where reserve1='1' and tmad_status='0' and tmad_kind=?";
		String[] fields = {"tmad_id","tmad_name"};
		array = JSONArray.fromObject(AccessDataBaseUtil.query(fields, sql, new Object[]{tmgd_id}));
		return array;
	}
	
	/** 
	 * 描述：selectTmaDictionaryById 根据药具Id查询药具信息
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 10, 2012  5:12:42 PM
	 * @author liu_zhaojun
	 */
	public Object selectTmaDictionaryById(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String tmad_id = jsonObject.getString("tmad_id");
		sql = "select tmad_description,tmad_spec,tmad_unit,tmad_company_name,tmad_batch_code,tmad_qgp,tmad_price from tma_dictionary where tmad_id=?";
		String[] fields = {"tmad_description","tmad_spec","tmad_unit","tmad_company_name","tmad_batch_code","tmad_qgp","tmad_price"};
		array = JSONArray.fromObject(AccessDataBaseUtil.query(fields, sql, new Object[]{tmad_id}));
		return array.toString().substring(1, array.toString().length()-1);
	}

	@Override
	public Object setRequest(HttpServletRequest request) throws Exception {
		this.request = request;
		return request;
	}

	@Override
	public Object updateBatch(Object jsonArray) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public Object recordCount(Object jsonArray) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object onCreate(Object jsonArray) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object onDestory(Object jsonArray) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object onInit(Object jsonArray) {
		// TODO Auto-generated method stub
		return null;
	}

}
